package mall

import (
	"context"
	"fmt"
	"github.com/samber/lo"
	"private-domain-overseas-service/app/business/api/internal/repository/mall"
	"private-domain-overseas-service/pkg/constant"
	"private-domain-overseas-service/pkg/status/bizmall"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/hzmallbrand"
	"private-domain-overseas-service/tools/ent/predicate"

	"private-domain-overseas-service/app/business/api/internal/svc"
	"private-domain-overseas-service/app/business/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type MallBrandListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 根据站点查询品牌信息
func NewMallBrandListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MallBrandListLogic {
	return &MallBrandListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MallBrandListLogic) MallBrandList(req *types.MallBrandListRequest) (resp *types.MallBrandListResponse, err error) {
	brandDao := mall.NewMallBrandDao(l.ctx, l.svcCtx)
	//构建查询条件
	brandsConditions := make([]predicate.HzMallBrand, 0)
	brandsConditions = append(brandsConditions, hzmallbrand.DeleteAtIsNil(), hzmallbrand.MallBrandSiteIDEQ(req.SiteId), hzmallbrand.MallBrandSiteShowEQ(bizmall.IsShow))
	//分页查询品牌信息
	brands, total, err := brandDao.MallBrandConditionsAllByPage(brandsConditions, req.Current, req.PageSize)
	if err != nil {
		return nil, xerr.ErrCodeMsg(xerr.ServerDataNotFoundError, fmt.Sprintf("查询品牌列表失败：%v", err))
	}
	mallBrands := lo.Map(brands, func(item *ent.HzMallBrand, _ int) *types.MallBrand {
		brandsParentConditions := make([]predicate.HzMallBrand, 0)
		brandsParentConditions = append(brandsParentConditions, hzmallbrand.IDEQ(int(item.MallBrandParentID)))
		prentBrand, _ := brandDao.MallBrandConditionsFirst(brandsParentConditions)
		brandIcon := ""
		if prentBrand.MallBrandIcon != "" {
			brandIcon = constant.MallGoodsImage + prentBrand.MallBrandIcon
		}
		return &types.MallBrand{
			Id:                  int64(item.ID),
			MallBrandIcon:       brandIcon,
			MallBrandName:       prentBrand.MallBrandName,
			MallBrandUrl:        item.MallBrandURL,
			MallBrandSort:       item.MallBrandSort,
			BrandCommissionRate: item.BrandCommissionRate,
			MallBrandSiteStatus: item.MallBrandSiteStatus,
		}
	})

	resp = &types.MallBrandListResponse{
		List: mallBrands,
		Page: &types.PageResponse{
			Total:           total,
			PageSize:        req.PageSize,
			RequestPageSize: req.PageSize,
			Current:         req.Current,
		},
	}

	return resp, nil
}
